<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - LinkUp管理后台</title>
    <link rel="stylesheet" th:href="@{/static/css/common.css}">
    <style>
        body {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }

        .manage-container {
            max-width: 1400px;
            margin: 80px auto 40px;
            padding: 0 20px;
        }

        .manage-header {
            background: rgba(255, 255, 255, 0.98);
            padding: 25px 30px;
            border-radius: 15px 15px 0 0;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .manage-header h1 {
            margin: 0;
            font-size: 26px;
            color: #f5576c;
        }

        .header-actions {
            display: flex;
            gap: 15px;
            align-items: center;
        }

        .search-box {
            display: flex;
            gap: 10px;
        }

        .search-input {
            padding: 10px 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            width: 250px;
            font-size: 14px;
        }

        .btn-search,
        .btn-add {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-search {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
        }

        .btn-add {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-search:hover,
        .btn-add:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        .table-container {
            background: white;
            border-radius: 0 0 15px 15px;
            padding: 30px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
        }

        .user-table {
            width: 100%;
            border-collapse: collapse;
        }

        .user-table thead {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
        }

        .user-table th {
            padding: 15px;
            text-align: left;
            font-weight: 600;
        }

        .user-table th:first-child {
            border-radius: 10px 0 0 0;
        }

        .user-table th:last-child {
            border-radius: 0 10px 0 0;
        }

        .user-table tbody tr {
            border-bottom: 1px solid #f0f0f0;
            transition: all 0.3s ease;
        }

        .user-table tbody tr:hover {
            background: #fef5f8;
        }

        .user-table td {
            padding: 15px;
        }

        .user-avatar {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid #f5576c;
        }

        .user-info {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .user-details .name {
            font-weight: 600;
            color: #333;
        }

        .user-details .account {
            font-size: 13px;
            color: #999;
        }

        .status-badge {
            padding: 5px 12px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: 600;
        }

        .status-normal {
            background: #e7f9ed;
            color: #67c23a;
        }

        .status-disabled {
            background: #fef0f0;
            color: #f56c6c;
        }

        .action-btns {
            display: flex;
            gap: 8px;
        }

        .btn-action {
            padding: 6px 12px;
            border: none;
            border-radius: 6px;
            font-size: 13px;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-edit {
            background: #409eff;
            color: white;
        }

        .btn-delete {
            background: #f56c6c;
            color: white;
        }

        .btn-disable {
            background: #e6a23c;
            color: white;
        }

        .btn-enable {
            background: #67c23a;
            color: white;
        }

        .btn-action:hover {
            opacity: 0.8;
        }

        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 10px;
            margin-top: 20px;
        }

        .page-btn {
            padding: 8px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            background: white;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .page-btn:hover {
            background: #f093fb;
            color: white;
            border-color: #f093fb;
        }

        .page-btn.active {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            border-color: #f093fb;
        }

        .page-info {
            color: #666;
            font-size: 14px;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
        }

        .modal.show {
            display: flex;
        }

        .modal-content {
            background: white;
            border-radius: 15px;
            width: 500px;
            max-width: 90%;
            padding: 30px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
        }

        .modal-header {
            font-size: 22px;
            font-weight: bold;
            color: #f5576c;
            margin-bottom: 20px;
        }

        .modal-body {
            margin-bottom: 20px;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .btn-cancel,
        .btn-confirm {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
        }

        .btn-cancel {
            background: #ddd;
            color: #666;
        }

        .btn-confirm {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #999;
        }
    </style>
</head>
<body>
    <nav class="navbar">
        <div class="nav-container">
            <div class="nav-logo">🎮 LinkUp 管理后台</div>
            <div class="nav-menu">
                <a th:href="@{/admin/home}">首页</a>
                <a th:href="@{/admin/user/list}" class="active">用户管理</a>
                <a href="#" onclick="logout()">退出</a>
            </div>
        </div>
    </nav>

    <div class="manage-container">
        <div class="manage-header">
            <h1>👥 用户管理</h1>
            <div class="header-actions">
                <div class="search-box">
                    <input type="text" id="searchKeyword" class="search-input" 
                           placeholder="搜索账号/昵称/手机号" onkeypress="if(event.keyCode==13) searchUsers()">
                    <button class="btn-search" onclick="searchUsers()">🔍 搜索</button>
                </div>
                <button class="btn-add" onclick="showAddModal()">➕ 添加用户</button>
            </div>
        </div>

        <div class="table-container">
            <div id="loadingMessage" class="loading">
                ⏳ 加载中...
            </div>

            <table class="user-table" id="userTable" style="display: none;">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户信息</th>
                        <th>手机号</th>
                        <th>总积分</th>
                        <th>游戏统计</th>
                        <th>状态</th>
                        <th>注册时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="userTableBody">
                    <!-- 动态加载 -->
                </tbody>
            </table>

            <div class="pagination" id="pagination" style="display: none;">
                <!-- 动态生成分页 -->
            </div>
        </div>
    </div>

    <!-- 添加/编辑用户模态框 -->
    <div id="userModal" class="modal">
        <div class="modal-content">
            <div class="modal-header" id="modalTitle">添加用户</div>
            <div class="modal-body">
                <input type="hidden" id="userId">
                <div class="form-group">
                    <label>手机号 <span class="required">*</span></label>
                    <input type="text" id="userPhone" class="form-control" placeholder="请输入手机号">
                </div>
                <div class="form-group">
                    <label>密码 <span class="required">*</span></label>
                    <input type="password" id="userPassword" class="form-control" placeholder="请输入密码">
                </div>
                <div class="form-group">
                    <label>昵称 <span class="required">*</span></label>
                    <input type="text" id="userNickname" class="form-control" placeholder="请输入昵称">
                </div>
                <div class="form-group">
                    <label>状态</label>
                    <select id="userStatus" class="form-control">
                        <option value="0">正常</option>
                        <option value="1">禁用</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-cancel" onclick="closeModal()">取消</button>
                <button class="btn-confirm" onclick="saveUser()">保存</button>
            </div>
        </div>
    </div>

    <footer class="footer">
        <div class="footer-content">
            <p>&copy; 2025 LinkUp 连连看管理后台</p>
        </div>
    </footer>

    <script>
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 0;

        // 加载用户列表
        function loadUsers(page = 1) {
            currentPage = page;
            const keyword = document.getElementById('searchKeyword').value;
            
            fetch(`/admin/user/data?page=${page}&size=${pageSize}&keyword=${keyword}`)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        const result = data.data;
                        totalPages = result.pages;
                        renderUserTable(result.list);
                        renderPagination(result.page, result.pages, result.total);
                    } else {
                        alert('加载失败：' + data.message);
                    }
                })
                .catch(error => {
                    console.error('加载失败', error);
                    alert('网络错误');
                });
        }

        // 渲染用户表格
        function renderUserTable(users) {
            const tbody = document.getElementById('userTableBody');
            tbody.innerHTML = '';

            if (users.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" style="text-align:center;padding:40px;color:#999;">暂无数据</td></tr>';
            } else {
                users.forEach(user => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                        <td>${user.id}</td>
                        <td>
                            <div class="user-info">
                                <img src="${user.avatar || '/static/images/default-avatar.png'}" class="user-avatar">
                                <div class="user-details">
                                    <div class="name">${user.nickname}</div>
                                    <div class="account">${user.account}</div>
                                </div>
                            </div>
                        </td>
                        <td>${user.phone}</td>
                        <td><strong>${user.totalScore}</strong></td>
                        <td>
                            总：${user.gameCount} | 
                            胜：${user.winCount} | 
                            负：${user.loseCount}
                        </td>
                        <td>
                            <span class="status-badge ${user.status === 0 ? 'status-normal' : 'status-disabled'}">
                                ${user.status === 0 ? '正常' : '禁用'}
                            </span>
                        </td>
                        <td>${formatDate(user.createTime)}</td>
                        <td>
                            <div class="action-btns">
                                <button class="btn-action btn-edit" onclick="editUser(${user.id})">编辑</button>
                                ${user.status === 0 ? 
                                    `<button class="btn-action btn-disable" onclick="toggleStatus(${user.id}, 1)">禁用</button>` :
                                    `<button class="btn-action btn-enable" onclick="toggleStatus(${user.id}, 0)">启用</button>`
                                }
                                <button class="btn-action btn-delete" onclick="deleteUser(${user.id})">删除</button>
                            </div>
                        </td>
                    `;
                    tbody.appendChild(tr);
                });
            }

            document.getElementById('loadingMessage').style.display = 'none';
            document.getElementById('userTable').style.display = 'table';
        }

        // 渲染分页
        function renderPagination(currentPage, totalPages, totalCount) {
            const pagination = document.getElementById('pagination');
            pagination.innerHTML = '';

            if (totalPages <= 1) {
                pagination.style.display = 'none';
                return;
            }

            pagination.style.display = 'flex';

            // 上一页
            if (currentPage > 1) {
                pagination.innerHTML += `<button class="page-btn" onclick="loadUsers(${currentPage - 1})">上一页</button>`;
            }

            // 页码
            for (let i = 1; i <= Math.min(totalPages, 10); i++) {
                pagination.innerHTML += `<button class="page-btn ${i === currentPage ? 'active' : ''}" onclick="loadUsers(${i})">${i}</button>`;
            }

            // 下一页
            if (currentPage < totalPages) {
                pagination.innerHTML += `<button class="page-btn" onclick="loadUsers(${currentPage + 1})">下一页</button>`;
            }

            pagination.innerHTML += `<span class="page-info">共 ${totalCount} 条</span>`;
        }

        // 搜索用户
        function searchUsers() {
            loadUsers(1);
        }

        // 显示添加模态框
        function showAddModal() {
            document.getElementById('modalTitle').textContent = '添加用户';
            document.getElementById('userId').value = '';
            document.getElementById('userPhone').value = '';
            document.getElementById('userPassword').value = '';
            document.getElementById('userNickname').value = '';
            document.getElementById('userStatus').value = '0';
            document.getElementById('userModal').classList.add('show');
        }

        // 编辑用户
        function editUser(userId) {
            fetch(`/admin/user/detail/${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        const user = data.data;
                        document.getElementById('modalTitle').textContent = '编辑用户';
                        document.getElementById('userId').value = user.id;
                        document.getElementById('userPhone').value = user.phone;
                        document.getElementById('userPassword').value = user.password;
                        document.getElementById('userNickname').value = user.nickname;
                        document.getElementById('userStatus').value = user.status;
                        document.getElementById('userModal').classList.add('show');
                    } else {
                        alert('获取用户信息失败');
                    }
                })
                .catch(error => {
                    console.error('获取失败', error);
                    alert('网络错误');
                });
        }

        // 保存用户
        function saveUser() {
            const userId = document.getElementById('userId').value;
            const phone = document.getElementById('userPhone').value.trim();
            const password = document.getElementById('userPassword').value.trim();
            const nickname = document.getElementById('userNickname').value.trim();
            const status = parseInt(document.getElementById('userStatus').value);

            if (!phone || !password || !nickname) {
                alert('请填写所有必填项');
                return;
            }

            const url = userId ? '/admin/user/update' : '/admin/user/add';
            const userDTO = {
                id: userId ? parseInt(userId) : null,
                phone,
                password,
                nickname,
                status
            };

            fetch(url, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(userDTO)
            })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        alert(data.message || '操作成功');
                        closeModal();
                        loadUsers(currentPage);
                    } else {
                        alert(data.message || '操作失败');
                    }
                })
                .catch(error => {
                    console.error('保存失败', error);
                    alert('网络错误');
                });
        }

        // 删除用户
        function deleteUser(userId) {
            if (!confirm('确定要删除该用户吗？此操作不可恢复！')) {
                return;
            }

            fetch(`/admin/user/delete/${userId}`, {method: 'POST'})
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        alert('删除成功');
                        loadUsers(currentPage);
                    } else {
                        alert(data.message || '删除失败');
                    }
                })
                .catch(error => {
                    console.error('删除失败', error);
                    alert('网络错误');
                });
        }

        // 切换用户状态
        function toggleStatus(userId, status) {
            const action = status === 0 ? '启用' : '禁用';
            if (!confirm(`确定要${action}该用户吗？`)) {
                return;
            }

            fetch(`/admin/user/status/${userId}/${status}`, {method: 'POST'})
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        alert(data.message || '操作成功');
                        loadUsers(currentPage);
                    } else {
                        alert(data.message || '操作失败');
                    }
                })
                .catch(error => {
                    console.error('操作失败', error);
                    alert('网络错误');
                });
        }

        // 关闭模态框
        function closeModal() {
            document.getElementById('userModal').classList.remove('show');
        }

        // 格式化日期
        function formatDate(dateStr) {
            if (!dateStr) return '-';
            const date = new Date(dateStr);
            return date.toLocaleDateString('zh-CN');
        }

        // 退出登录
        function logout() {
            if (confirm('确定要退出登录吗？')) {
                window.location.href = '/admin/logout';
            }
        }

        // 页面加载时初始化
        window.onload = function() {
            loadUsers(1);
        };
    </script>
</body>
</html>

